<?php
/**
 * SME.Model.Behaviors.Switchable, Part of BIT.SMEJOB CMS
 * Functionality: update tinyInt fields of a database, usaully happened with ajax activities
 * @author: tomato at <wangshijun2010@gmail.com>
 * @version: 1.0
 * @started: 2010-01-15 08:15:07
*/

class SwitchableBehavior extends ModelBehavior{
    public $name = 'Switchable';
    public $settings = array();
    private $__defaultOptions = array(
        'fields' => array()
    );

    /**
     * Setup behaviour.
     *
     * @param Model $model
     * @param array $settings
     */
    public function setup(&$model, $settings = array()){
        if(!isset($this->settings[$model->alias])){
            if(empty($settings)){
                $this->settings[$model->alias] = $this->__defaultOptions;
            }elseif(is_array($settings)){
                $this->settings[$model->alias] = array_merge($this->__defaultOptions, $settings);
            }
        }
    }

    /**
     * Switch on an field, eg, set an tinyInt field to true(1)
     *
     * @param Model $model
     * @param int $id
     * @param string $field
     */
    public function switchOn(&$model, $field=null, $id=null){
        if(empty($field)){ return false; }
        if(empty($id) && empty($model->id)){ return false; }

        if(in_array($field, $this->settings[$model->alias]['fields']) || !$model->hasField($field)){
            return false;
        }

        if(!empty($id)){
            $model->id = $id;
        }

        return $model->saveField($field, 1);
    }

    /**
     * Switch off an field, eg, set an tinyInt field to false(0)
     *
     * @param Model $model
     * @param int $id
     * @param string $field
     */
    public function switchOff(&$model, $field=null, $id=null){
        if(empty($field)){ return false; }
        if(empty($id) && empty($model->id)){ return false; }

        if(in_array($field, $this->settings[$model->alias]['fields']) || !$model->hasField($field)){
            return false;
        }

        if(!empty($id)){
            $model->id = $id;
        }

        return $model->saveField($field, 0);
    }
}

?>